from decimal import Decimal
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from goods.models import SKU
from orders.models import OrderGoods, OrderInfo
from orders.serializer import OrderSettlement, OrderSaveSerializer, SaveCommentSerializer, OrderDetailSerializer


# GET /orders/settlement/
class OrderSettlementView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self,request):
        '''获取登录用户结算商品的数据:'''
        user = request.user
        # 1.从登录用户的redis购物车记录中获取用户购物车中被勾选的商品id和对应数量count
        redis_conn = get_redis_connection('cart')

        cart_userid = 'cart_%s' % user.id
        # 获取reids-hash中所有的属性和值
        # {
        #     b'<sku_id>': b'<count>',
        #     ...
        # }
        cart_redis = redis_conn.hgetall(cart_userid)
        # 从redis set中获取用户勾选的商品id
        cart_selected_userid = 'cart_selected_%s' % user.id
        # (b'<sku_id>', ...)
        cart_selected_redis = redis_conn.smembers(cart_selected_userid)

        # 2.根据商品id获取对应的商品数据并组织运费
        # 组织数据:redis中取出来是bytes类型-->遍历转换int
        cart_dict={}
        for sku_id, count in cart_redis.items():
            cart_dict[int(sku_id)] = int(count)
        # 查询数据库id__in=[列表]
        skus = SKU.objects.filter(id__in=cart_selected_redis)
        # sku对象没有count属性-->遍历添加属性
        for sku in skus:
            sku.count = cart_dict[sku.id]

        # 3.将数据序列化并返回
        serializer = OrderSettlement(skus,many=True)
        # 组织响应数据
        freight = Decimal(10.0)
        response_data = {
            'freight':freight,
            'skus':serializer.data
        }
        return Response(response_data)

#  /orders/
class SaveOrderViewSet(CreateModelMixin,GenericViewSet,ListModelMixin):
    permission_classes = [IsAuthenticated]
    # serializer_class = OrderSaveSerializer
    def get_queryset(self):
        return OrderInfo.objects.filter(user=self.request.user.id)

    def get_serializer_class(self):
        """获取视图所使用的序列化器类"""
        if self.action == 'list':
            return OrderDetailSerializer
        else:
            return OrderSaveSerializer
    # def post(self,request):
    #     """订单保存到数据库接口"""
    #     # 1 获取参数并校验(收获地址id(收获地址是否存在),支付方式pay_method是否合法)
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     # 2 保存订单
    #     serializer.save()
    #     # 2.1 将订单数据保存到订单基本信息表中
    #     # 2.2 将订单的商品保存到订单商品表中
    #     # 2.3 将购物车redis中已提交的商品数据进行清除
    #     # 3 返回订单编号数据
    #     return Response(serializer.data,status=status.HTTP_201_CREATED)
    # get  /orders/
    # def list(self, request):
    #     """用户订单展示接口"""
    #     # 查询出和当前登录用户所有的订单信息
    #     orders = OrderInfo.objects.filter(user=request.user.id)
    #
    #     serializer = self.get_serializer(orders, many=True)
    #     data = {
    #         'count':len(orders), # 该用户所有的订单数量
    #         'results': serializer.data # 订单信息
    #     }
    #
    #     return Response(data)

# POST /orders/(?P<order_id>\d+)/comments/
# 请求参数:   请求头传递JWTtoken
# order: 订单编号
# sku: 订单商品id,
# comment: 商品评论内容,
# score: 满意度,
# is_anonymous: 是否匿名评价
# 响应参数: 评价成功
class SaveCommentView(APIView):
    permission_classes = [IsAuthenticated]
    """订单商品评论保存"""
    def post(self,request,order_id):
        # 获取订单信息对象
        # order = OrderInfo.objects.get(order_id=order_id)
        # 获取订单商品对象
        # order_sku = OrderGoods.objects.get(order = order,sku = request.data.get('sku'))
        order_good_id = request.data.get('sku',None)
        if order_good_id is None:
            return Response({'message':'参数不全'})
        order_sku = OrderGoods.objects.get(id=order_good_id)
        # 进行校验
        serializer = SaveCommentSerializer(order_sku,data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response({'message':'评价成功'})

# GET skus/(?P<sku_id>\d+)/comments/
# 请求参数: sku_id
# 响应参数:comment,score,username
# [
# {comment:评论,score:星级,username:用户名},
# ....
# ]
class ListCommentView(APIView):
    # 如果说评论很多,已经配置了全局分页类,进行分页展示
    def get(self,request,sku_id):
        """商品详情展示界面的评论展示"""
        # 查询出要展示的商品对象
        sku = SKU.objects.get(id=sku_id)
        order_skus = OrderGoods.objects.filter(sku=sku)

        # 组织响应参数
        comments_list = []
        for order_sku in order_skus:
            comments_dict = {}
            if order_sku.is_commented:
                comments_dict['comment']=order_sku.comment
                comments_dict['score'] = order_sku.score
                # 获取订单信息对象
                order = order_sku.order
                #　根据订单信息对象查询用户对象
                user = order.user
                comments_dict['username'] = user.username
                # 如果是匿名评价要加密用户名
                if order_sku.is_anonymous:
                    comments_dict['username'] = '匿名用户'
                comments_list.append(comments_dict)
        return Response(data=comments_list)

# GET orders/(?P<order_id>\d+)/uncommentgoods/
# 请求参数 JWT token
# 返回值: 属于当前订单的所有未评价的订单商品
class GetUncommentOrderGoodsView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self,request,order_id):
        """获取用户的未评价的订单商品"""
        # 获取订单商品对象(多个)
        order_skus = OrderGoods.objects.filter(order = order_id)
        # skus=
        # [
        #     {'id':"sku模型类id",
        #     'price':"订单商品单价"
        #     'sku':{
        #          'id':"订单商品模型类的id"",
        #         'default_image_url':"订单商品的默认图片",
        #         'name':"订单商品的名字"
        #             }
        #      }
        #     ......
        # ]
        # # 组织未评论的订单商品
        skus = []
        for order_sku in order_skus:
            uncomments_dict = {}
            if not order_sku.is_commented:
                uncomments_dict['id']=order_sku.sku.id
                uncomments_dict['price'] = order_sku.sku.price
                uncomments_dict['sku'] = {
                    'id':order_sku.id,
                    'default_image_url':order_sku.sku.default_image_url,
                    'name':order_sku.sku.name
                                          }
                skus.append(uncomments_dict)
        return Response(data=skus)

























